import 'package:flutter/material.dart';
import 'package:study_app/utils/common.dart';

enum LoadStatus {
  loading, // 加载中
  loaded, // 空闲
  all, // 没有新数据了
}


class CommonList extends StatefulWidget {
  int refreshHandler;
  final void Function(
      int page, int pageSize, Function success, Function failure) fetchData;
  final Widget Function(dynamic) renderItem;
  final Widget Function(dynamic, int index, bool isLastIndex)? renderItemIndex;
  CommonList(
      {Key? key,
      required this.renderItem,
      required this.fetchData,
      this.renderItemIndex,
      this.refreshHandler = 0})
      : super(key: key);
  @override
  State<StatefulWidget> createState() => _CommonListState();
}

class _CommonListState extends State<CommonList> {
  final ScrollController _scrollController = ScrollController();
  var array = [];
  var pageSize = 20;
  var page = 1;

  var loadStatus = LoadStatus.loaded;
  var isLived = false;

  @override
  void initState() {
    super.initState();
    isLived = true;
    addLisener();
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      fetchData(true);
    });
  }

  @override
  void didUpdateWidget(covariant CommonList oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.refreshHandler < widget.refreshHandler) {
      WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
        page = 1;
        widget.fetchData(page, pageSize, success, failure);
      });
    }
  }

  void addLisener() {
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        if (loadStatus == LoadStatus.loaded) {
          loadData(false);
        } else if (loadStatus == LoadStatus.all) {
          // Toast.showOnContext(context, "没有更多数据了");
        } else {
          debugPrint("正在加载中...");
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    isLived = false;
    _scrollController.dispose();
  }

  failure(msg) {
    // toast提示error
  }

  success(List data) {
    if (isLived == false) {
      return;
    }
    bool isArr = data is List;
    if (!isArr) {
      debugPrint("传入的列表参数不是数组");
      return;
    }
    var tempLoadStatus = LoadStatus.loaded;
    if (data.length < pageSize) {
      tempLoadStatus = LoadStatus.all;
    }
    if (page == 1) {
      array.clear();
    }
    if (array.isNotEmpty) {
      if (tempLoadStatus == LoadStatus.all) {
        data.add("没有更多数据了~");
      }
    }
    page = page + 1;
    // setState(() {
    //   array.addAll(data);
    //   loadStatus = tempLoadStatus;
    // });
  }

  toLoading() {
    if (isLived == false) {
      return;
    }
    if (loadStatus == LoadStatus.loaded) {
      setState(() {
        loadStatus = LoadStatus.loading;
      });
    }
  }

  fetchData(bool isPullDown) {
    if (isLived == false) {
      return;
    }
    var x = isPullDown ? "下" : "上";
    debugPrint("$x拉加载");
    if (isPullDown) {
      page = 1;
    }
    widget.fetchData(page, pageSize, success, failure);
  }

  //上拉加载
  void loadData(bool isPullDown) {
    toLoading();
    fetchData(isPullDown);
  }

  Widget _makeListView() {
    int listLen = array.isEmpty ? 1 : array.length;

    return ListView.builder(
        controller: _scrollController,
        physics: const AlwaysScrollableScrollPhysics(),
        itemCount: listLen,
        itemBuilder: _itemBuilder);
  }

  Widget _listFooter(String xx) {
    return Container(
      height: 30,
      decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(
              top: BorderSide(
                  color: Colors.grey, width: 1, style: BorderStyle.solid))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            xx,
            style: const TextStyle(fontSize: 15, color: Color(0xff666666)),
          )
        ],
      ),
    );
  }

  Widget _itemBuilder(context, index) {
    if (array.isEmpty) {
      return _makeErrorView();
    }
    var xx = array[index];
    if (xx is String) {
      return _listFooter(xx);
    } else {
      if (widget.renderItemIndex == null) {
        return widget.renderItem(xx);
      } else {
        bool isLast = array.length == index + 1;
        var last = array.last;
        if (last is String) {
          isLast = array.length == index + 2;
        }
        return widget.renderItemIndex!(xx, index, isLast);
      }
    }
  }

  /// 获取屏幕高度（出来顶部导航和底部安全区）
  _getScreenHeight() {
    var xx = Common.screenHeight -
        Common.bottomBarHeight -
        Common.statusBarHeight -
        84.0 -
        49.0;
    return xx;
  }

  Widget _makeErrorView() {
    double w = 210;
    double prex = 314.0 / 231.0;
    double h = w / prex;
    return SizedBox(
      height: _getScreenHeight(),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: const [
          Icon(Icons.ac_unit),
          Text(
            "暂无相关数据",
            style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w400,
                color: Color(0xFF333333)),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        child: _makeListView(),
        onRefresh: () async {
          loadData(true);
        });
  }
}
